#!/usr/bin/env node
var lt_client = require('../client');
var open_url = require('openurl');

var argv = require('yargs')
    .usage('Usage: $0 --port [num] <options>')
    .env(true)
    .option('h', {
        alias: 'host',
        describe: 'Upstream server providing forwarding',
        default: 'https://localtunnel.me',
    })
    .option('s', {
        alias: 'subdomain',
        describe: 'Request this subdomain'
    })
    .option('l', {
        alias: 'local-host',
        describe: 'Tunnel traffic to this host instead of localhost, override Host header to this host'
    })
    .options('o', {
        alias: 'open',
        describe: 'opens url in your browser'
    })
    .option('p', {
        alias: 'port',
        describe: 'Internal http server port',
    })
    .option('print-requests', {
        describe: 'Print basic request info',
    })
    .require('port')
    .boolean('print-requests')
    .help('help', 'Show this help and exit')
    .version(require('../package').version)
    .argv;

if (typeof argv.port !== 'number') {
    require('yargs').showHelp();
    console.error('port must be a number');
    process.exit(1);
}

var opt = {
    host: argv.host,
    port: argv.port,
    local_host: argv['local-host'],
    subdomain: argv.subdomain,
};

const PrintRequests = argv['print-requests'];

lt_client(opt.port, opt, function(err, tunnel) {
    if (err) {
        throw err;
    }

    console.log('your url is: %s', tunnel.url);

    if (argv.open) {
        open_url.open(tunnel.url);
    }

    tunnel.on('error', function(err) {
        throw err;
    });

    if (PrintRequests) {
        tunnel.on('request', function(info) {
            console.log(new Date().toString(), info.method, info.path);
        });
    }
});

// vim: ft=javascript
